/**
 * SignValidator.java 
 * Copyright © 2014-2016, 杭州泊享网络科技有限公司
 * 
 * @author Liu Tao
 * @create 2015年5月11日
 */
package com.pshare.framework.validator;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.pshare.constant.ReturnMsg;
import com.pshare.framework.annotation.SignCheck;
import com.pshare.util.SysPropertyUtils;

/**
 * 参数签名验证
 */
public class SignValidator implements ConstraintValidator<SignCheck, CharSequence> {

	private static String SIGN_CHECK = SysPropertyUtils.getProperty("sys.signcheck");
	
	@Override
	public void initialize(SignCheck constraintAnnotation) {

	}

	@Override
	public boolean isValid(CharSequence object, ConstraintValidatorContext constraintContext) {
//		if (StringUtils.isBlank(SIGN_CHECK) || "0".equals(SIGN_CHECK)) {
//			return true;
//		}
		
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		final String method = request.getMethod();
		// 只对POST PUT请求的json格式数据做验证
		// 签名验证暂时这么处理，后面有时间再做调整
		if (!"POST".equalsIgnoreCase(method) && !"PUT".equalsIgnoreCase(method)) {
			return true;
		}
		if (!"application/json".equalsIgnoreCase(request.getContentType())) {
			return true;
		}
		
		if (StringUtils.isBlank(object))
			return false;
		
		boolean valid = object.toString().equalsIgnoreCase("true");

        if(!valid) {
            constraintContext.disableDefaultConstraintViolation();
            constraintContext.buildConstraintViolationWithTemplate(ReturnMsg.WRONG_SIGN).addConstraintViolation();
        }
        
        return valid;
	}

}
